package com.association.main.interceptor;

import com.association.main.domain.Users;
import com.association.main.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

//登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {


    private static final List<String> ADMIN_URLS = Arrays.asList("/admin/**");
    private static final List<String> USER_URLS = Arrays.asList("/user/**");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().toUpperCase(Locale.ROOT).equals("OPTIONS")){
            return true;
        }
        if(request.getRequestURI().contains("images")){
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        if(token==null){
            return false;
        }else{
            boolean b = JwtUtil.checkToken(token);
            if(b){
                Users users = new Users();
                String userType = JwtUtil.getUserType(token);
                users.setId(JwtUtil.getUserId(token));
                users.setRole(userType);
                users.setUsername(JwtUtil.getMemberIdByJwtToken(token));
                String jwtToken = JwtUtil.getJwtToken(users);
                //防止用户跨权
                response.addHeader("token",jwtToken);
                if (userType.equals("0") && !request.getRequestURI().startsWith("/front/")) {
                    response.setHeader("code", "50008");
                    return false;
                }


                return true;
            }else{
                response.setHeader("code","50008");
                return false;
            }
        }
    }
}
